/**
 *
 * @type {MongoClient}
 */

const MongoClient = require('mongodb').MongoClient;
const log = require('../common/log');


class CURD {
    constructor() {}
    // 库名
    dbName = 'xhpx';
    url = "mongodb://localhost:27017/"+this.dbName;

    // 查
    find(msg) {
        msg.field= !msg.field ? {} : msg.field;
        return new Promise((resolve, reject) => {
            MongoClient.connect(this.url, (err, dbs) => {
                if (err) throw err;

                dbs.db(this.dbName)
                    .collection(msg.table)
                    .find(JSON.parse(msg.field))
                    .toArray()
                    .then(function (result) {
                        resolve(result);
                        dbs.close();
                    }, function (err) {
                        console.log(err.message);
                    })
            });
        })
    }

    // 增
    add (msg) {
        return new Promise((resolve, reject) => {
            if (!msg.field) reject('字段不能为空！');

            MongoClient.connect(this.url,  (err, dbs) => {
                if (err) throw err;

                dbs.db(this.dbName)
                    .collection(msg.table)
                    .insertOne(msg.field)
                    .then(function (result) {
                        resolve(result);
                        dbs.close();
                    }, function (err) {
                        console.log(err.message);
                    })
            });
        })
    }

    // 改：修改、删除字段
    chang (msg) {
        // log.msg(msg)
        return new Promise((resolve, reject) => {
            if (!msg.field) reject('字段不能为空！');

            MongoClient.connect(this.url,  (err, dbs) => {
                const collection = dbs.db(this.dbName).collection(msg.table)
                if (msg.ctrl=='set') {
                    collection.updateOne(msg.where, { $set: msg.field })
                        .then(function (result) {
                            resolve(result);
                            dbs.close();
                        }, function (err) {
                            console.log(err.message);
                        })
                }
                if (msg.ctrl=='del') {
                    collection.updateOne(msg.where, { $unset: msg.field })
                        .then(function (result) {
                            resolve(result);
                            dbs.close();
                        }, function (err) {
                            console.log(err.message);
                        })
                }
            });
        });
    }
}

module.exports = new CURD();
